package com.cat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cat.constant.MessageConstant;
import com.cat.constant.StatusConstant;
import com.cat.dto.EmployeeInfoDTO;
import com.cat.dto.PageDTO;
import com.cat.entity.Employee;
import com.cat.entity.LoginInfo;
import com.cat.exception.AccountLockedException;
import com.cat.exception.AccountNotFoundException;
import com.cat.exception.PasswordErrorException;
import com.cat.mapper.EmployeeMapper;
import com.cat.query.DepartmentQuery;
import com.cat.service.EmployeeService;
import com.cat.vo.EmployeeVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    private final EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param loginInfo
     * @return
     */
    @Override
    public Employee login(LoginInfo loginInfo) {
        String username = loginInfo.getUsername();
        String password = loginInfo.getPassword();
//        String clientId = loginInfo.getClientId();

//        Employee sysClient = getById((Serializable) clientId);
//        CommonResponseEnum.INVALID_ID.assertNull(sysClient);

        LambdaQueryWrapper<Employee> wrapper = new QueryWrapper<Employee>().lambda();
        wrapper.eq(Employee::getUsername, username);

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.selectOne(wrapper);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3.密码对比
        if (!password.equals(employee.getPassword())) {
            LambdaQueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<Employee>().lambda();
            employeeQueryWrapper.eq(Employee::getId, employee.getId());

            // 如果密码不对，错误次数加一
            employeeMapper.updateLoginErrorCount(1, employeeQueryWrapper);

            if (employee.getLoginErrorCount() > 3) {
                Employee build = Employee.builder().id(employee.getId())
                        .status(StatusConstant.DISABLE)
                        .build();

                employeeMapper.updateById(build);
            }

            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR + "还有" + (4 - employee.getLoginErrorCount()) + "次机会");
        }

        if (employee.getLoginErrorCount() != 0) {
            Employee build = Employee.builder()
                    .id(employee.getId())
                    .loginErrorCount(0)
                    .build();

            employeeMapper.updateById(build);
        }

        Employee build = Employee.builder()
                .id(employee.getId())
                .lastLoginTime(LocalDateTime.now())
                .build();
        employeeMapper.updateById(build);

        return employee;
    }

    /**
     * 根据部门id查询员工
     *
     * @param departmentQuery
     * @return
     */
    @Override
    public PageDTO<EmployeeVO> getByDepartmentId(DepartmentQuery departmentQuery) {
        Page<Employee> employeePage = new Page<>(departmentQuery.getPageNum(), departmentQuery.getPageSize());

        Page<Employee> page = lambdaQuery()
                .eq(departmentQuery.getDepartmentId() != null, Employee::getDepartmentId, departmentQuery.getDepartmentId())
                .ne(Employee::getRoles, "admin")
                .eq(departmentQuery.getStatus() != null , Employee::getStatus,departmentQuery.getStatus())
                .like(departmentQuery.getUsername() != null , Employee::getUsername,departmentQuery.getUsername())
                .like(departmentQuery.getRealName() != null, Employee::getRealName,departmentQuery.getRealName())
                .eq(departmentQuery.getGender() != null, Employee::getGender,departmentQuery.getGender())
                .page(employeePage);

        PageDTO<EmployeeVO> employeeVOPageDTO = new PageDTO<>();
        employeeVOPageDTO.setPageNum(page.getCurrent());
        employeeVOPageDTO.setPageSize(page.getSize());
        employeeVOPageDTO.setTotal(page.getTotal());

        List<Employee> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            // Collections.emptyList() 返回一个空列表
            employeeVOPageDTO.setList(Collections.emptyList());
        } else {
            List<EmployeeVO> employeeVOS = BeanUtil.copyToList(records, EmployeeVO.class);
            employeeVOPageDTO.setList(employeeVOS);
        }

        return employeeVOPageDTO;
    }

    /**
     * 新增员工
     * @param employeeInfoDTO
     */
    @Override
    public void add(EmployeeInfoDTO employeeInfoDTO) {
        Employee employee = BeanUtil.copyProperties(employeeInfoDTO, Employee.class);
        employee.setRoles("employee");

        employeeMapper.insert(employee);

    }
}
